package com.kaka.bus.engine.amount.gongjijinamount;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.AppCompatSeekBar;
import android.util.Log;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.kaka.bus.R;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.BpmList;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.bean.Status;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.constant.UserConstant;
import com.kaka.bus.engine.borrow.face.FaceActivity;
import com.kaka.bus.engine.borrow.idcard.IdCardBackActivity;
import com.kaka.bus.engine.borrow.idcard.IdCardFrontActivity;
import com.kaka.bus.engine.borrow.person.PersonActivity;
import com.kaka.bus.engine.borrow.phone.PhoneActivity;
import com.kaka.bus.manager.BottomDialogManager;
import com.kaka.bus.view.AuthView;
import com.moxie.client.exception.ExceptionType;
import com.moxie.client.exception.MoxieException;
import com.moxie.client.manager.MoxieCallBack;
import com.moxie.client.manager.MoxieCallBackData;
import com.moxie.client.manager.MoxieContext;
import com.moxie.client.manager.MoxieSDK;
import com.moxie.client.model.MxParam;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;

public class GongJiJinActivity extends BaseActivity<GongJiJinPresenter> implements GongJiJinContract.View {
    private static final String TAG = "GongJiJinActivity";
    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_name)
    TextView mToolbarName;
    @BindView(R.id.limit_gjj)
    AuthView limit_gjjd;
    @BindView(R.id.seekbar)
    AppCompatSeekBar seekBar;
    @BindView(R.id.tv_right)
    TextView mTvRight;
    @BindView(R.id.tv_left)
    TextView mTvLeft;
    @BindView(R.id.tv_amount)
    TextView mTvAmount;
    @BindView(R.id.rl_select)
    RelativeLayout rl_select;
    @BindView(R.id.tv_month)
    TextView tv_month;
    @BindView(R.id.limit_terz)
    AuthView limit_terz;
    @BindView(R.id.limit_swipe)
    SwipeRefreshLayout mLimitSwipe;
    @BindView(R.id.limit_idcard)
    AuthView mLimitIdcard;
    @BindView(R.id.limit_person)
    AuthView mLimitPerson;
    @BindView(R.id.limit_face)
    AuthView mLimitFace;
    @BindView(R.id.limit_phone)
    AuthView mLimitPhone;
    private final static String PRODUCTID = "productId";

    private LinkedList<AuthView> mAuthViews = new LinkedList<>();
    private List<BpmList> mData;

    private String mProductId;
    private BottomDialogManager mDialogManager;
    private ArrayList<String> mMonth = new ArrayList<>();
    private MxParam mxParam;

    @Override
    public void bpmListSuccess(HttpWrapper<List<BpmList>> wrapper) {
        closeRefresh();
        if (Constant.SUCCESS_CODE.equals(wrapper.code)) {
            mData = wrapper.getData();
            if (mData == null) {
                return;
            }
            for (int i = 0; i < mData.size(); i++) {
                mAuthViews.get(i).setTips(mData.get(i).getNodeStatusName(), mData.get(i).getNodeStatus());
            }
        } else {
            showMessage(wrapper.getInfo());
        }
    }

    @Override
    public void checkBpmSuccess(HttpWrapper<Status> wrapper) {

    }

    @Override
    protected void initView() {
        super.initView();
        /**
         * swipe的下拉高度
         */
        mProductId = getIntent().getStringExtra(PRODUCTID);
        mLimitSwipe.setProgressViewEndTarget(false, 300);
        mLimitSwipe.setColorSchemeColors(getResources().getColor(R.color.toolbar_color));
        mToolbarName.setText("公积金贷");
        mDialogManager = new BottomDialogManager(this);
        seekBar.setProgress(19);
        mAuthViews.addLast(mLimitIdcard);
        mAuthViews.addLast(mLimitPerson);
        mAuthViews.addLast(mLimitFace);
        mAuthViews.addLast(mLimitPhone);

    }

    @Override
    protected void initDataOnStart() {
        super.initDataOnStart();
        mPresenter.bpmList(getUserId(), getToken(), mProductId);
    }

    @Override
    protected void initData() {
        super.initData();
        mMonth.add("三个月");
        mMonth.add("六个月");
        mMonth.add("十二个月");
        mDialogManager.setData(mMonth);
        mxParam = new MxParam();
        mxParam.setUserId(getUserId());
        mxParam.setApiKey(Constant.MOXIE_KEY);
    }

    @Override
    protected void initListener() {
        super.initListener();
        mToolbarBack.setOnClickListener(v -> {
            finish();
        });

        limit_gjjd.setOnClickListener(v -> {
            mxParam.setTaskType(MxParam.PARAM_TASK_FUND);
            MoxieSDK.getInstance().start(GongJiJinActivity.this, mxParam, new MoxieCallBack() {
                /**
                 *
                 *  物理返回键和左上角返回按钮的back事件以及sdk退出后任务的状态都通过这个函数来回调
                 *
                 * @param moxieContext       可以用这个来实现在魔蝎的页面弹框或者关闭魔蝎的界面
                 * @param moxieCallBackData  我们可以根据 MoxieCallBackData 的code来判断目前处于哪个状态，以此来实现自定义的行为
                 * @return 返回true表示这个事件由自己全权处理，返回false会接着执行魔蝎的默认行为(比如退出sdk)
                 *
                 *   # 注意，假如设置了MxParam.setQuitOnLoginDone(MxParam.PARAM_COMMON_YES);
                 *   登录成功后，返回的code是MxParam.ResultCode.IMPORTING，不是MxParam.ResultCode.IMPORT_SUCCESS
                 */
                @Override
                public boolean callback(MoxieContext moxieContext, MoxieCallBackData moxieCallBackData) {
                    /**
                     *  # MoxieCallBackData的格式如下：
                     *  1.1.没有进行账单导入，未开始！(后台没有通知)
                     *      "code" : MxParam.ResultCode.IMPORT_UNSTART, "taskType" : "mail", "taskId" : "", "message" : "", "account" : "", "loginDone": false, "businessUserId": ""
                     *  1.2.平台方服务问题(后台没有通知)
                     *      "code" : MxParam.ResultCode.THIRD_PARTY_SERVER_ERROR, "taskType" : "mail", "taskId" : "", "message" : "", "account" : "xxx", "loginDone": false, "businessUserId": ""
                     *  1.3.魔蝎数据服务异常(后台没有通知)
                     *      "code" : MxParam.ResultCode.MOXIE_SERVER_ERROR, "taskType" : "mail", "taskId" : "", "message" : "", "account" : "xxx", "loginDone": false, "businessUserId": ""
                     *  1.4.用户输入出错（密码、验证码等输错且未继续输入）
                     *      "code" : MxParam.ResultCode.USER_INPUT_ERROR, "taskType" : "mail", "taskId" : "", "message" : "密码错误", "account" : "xxx", "loginDone": false, "businessUserId": ""
                     *  2.账单导入失败(后台有通知)
                     *      "code" : MxParam.ResultCode.IMPORT_FAIL, "taskType" : "mail",  "taskId" : "ce6b3806-57a2-4466-90bd-670389b1a112", "account" : "xxx", "loginDone": false, "businessUserId": ""
                     *  3.账单导入成功(后台有通知)
                     *      "code" : MxParam.ResultCode.IMPORT_SUCCESS, "taskType" : "mail",  "taskId" : "ce6b3806-57a2-4466-90bd-670389b1a112", "account" : "xxx", "loginDone": true, "businessUserId": "xxxx"
                     *  4.账单导入中(后台有通知)
                     *      "code" : MxParam.ResultCode.IMPORTING, "taskType" : "mail",  "taskId" : "ce6b3806-57a2-4466-90bd-670389b1a112", "account" : "xxx", "loginDone": true, "businessUserId": "xxxx"
                     *
                     *  code           :  表示当前导入的状态
                     *  taskType       :  导入的业务类型，与MxParam.setTaskType()传入的一致
                     *  taskId         :  每个导入任务的唯一标识，在登录成功后才会创建
                     *  message        :  提示信息
                     *  account        :  用户输入的账号
                     *  loginDone      :  表示登录是否完成，假如是true，表示已经登录成功，接入方可以根据此标识判断是否可以提前退出
                     *  businessUserId :  第三方被爬取平台本身的userId，非商户传入，例如支付宝的UserId
                     */
                    if (moxieCallBackData != null) {
                        Log.d(TAG, "MoxieSDK Callback Data : " + moxieCallBackData.toString());
                        switch (moxieCallBackData.getCode()) {
                            /**
                             * 账单导入中
                             *
                             * 如果用户正在导入魔蝎SDK会出现这个情况，如需获取最终状态请轮询贵方后台接口
                             * 魔蝎后台会向贵方后台推送Task通知和Bill通知
                             * Task通知：登录成功/登录失败
                             * Bill通知：账单通知
                             */
                            case MxParam.ResultCode.IMPORTING:
                                if (moxieCallBackData.isLoginDone()) {
                                    Toast.makeText(mContext, moxieCallBackData.getTaskId(), Toast.LENGTH_SHORT).show();
                                    //状态为IMPORTING, 且loginDone为true，说明这个时候已经在采集中，已经登录成功
                                    Log.d(TAG, "任务已经登录成功，正在采集中，SDK退出后不会再回调任务状态，任务最终状态会从服务端回调，建议轮询APP服务端接口查询任务/业务最新状态");
                                    Log.d(TAG, moxieCallBackData.toString());

                                } else {
                                    //状态为IMPORTING, 且loginDone为false，说明这个时候正在登录中
                                    Log.d(TAG, "任务正在登录中，SDK退出后不会再回调任务状态，任务最终状态会从服务端回调，建议轮询APP服务端接口查询任务/业务最新状态");
                                }
                                break;
                            /**
                             * 任务还未开始
                             *
                             * 假如有弹框需求，可以参考 {@link BigdataFragment#showDialog(MoxieContext)}
                             *
                             * example:
                             *  case MxParam.ResultCode.IMPORT_UNSTART:
                             *      showDialog(moxieContext);
                             *      return true;
                             * */
                            case MxParam.ResultCode.IMPORT_UNSTART:
                                Log.d(TAG, "任务未开始");
                                break;
                            case MxParam.ResultCode.THIRD_PARTY_SERVER_ERROR:
                                Toast.makeText(GongJiJinActivity.this, "导入失败(平台方服务问题)", Toast.LENGTH_SHORT).show();
                                break;
                            case MxParam.ResultCode.MOXIE_SERVER_ERROR:
                                Toast.makeText(GongJiJinActivity.this, "导入失败(魔蝎数据服务异常)", Toast.LENGTH_SHORT).show();
                                break;
                            case MxParam.ResultCode.USER_INPUT_ERROR:
                                Toast.makeText(GongJiJinActivity.this, "导入失败(" + moxieCallBackData.getMessage() + ")", Toast.LENGTH_SHORT).show();
                                break;
                            case MxParam.ResultCode.IMPORT_FAIL:
                                Toast.makeText(GongJiJinActivity.this, "导入失败", Toast.LENGTH_SHORT).show();
                                break;
                            case MxParam.ResultCode.IMPORT_SUCCESS:
                                Log.d(TAG, "任务采集成功，任务最终状态会从服务端回调，建议轮询APP服务端接口查询任务/业务最新状态");

                                //根据taskType进行对应的处理
                                switch (moxieCallBackData.getTaskType()) {
                                    case MxParam.PARAM_TASK_FUND:
                                        Log.d("根据taskType进行对应的处理", moxieCallBackData.toString());

                                        Toast.makeText(GongJiJinActivity.this, "公积金导入成功", Toast.LENGTH_SHORT).show();
                                        break;
                                    default:
                                        Toast.makeText(GongJiJinActivity.this, "导入成功", Toast.LENGTH_SHORT).show();
                                }
                                moxieContext.finish();
                                return true;
                        }
                    }
                    return false;
                }

                /**
                 * @param moxieContext    可能为null，说明还没有打开魔蝎页面，使用前要判断一下
                 * @param moxieException  通过exception.getExceptionType();来获取ExceptionType来判断目前是哪个错误
                 */
                @Override
                public void onError(MoxieContext moxieContext, MoxieException moxieException) {
                    super.onError(moxieContext, moxieException);
                    if (moxieException.getExceptionType() == ExceptionType.SDK_HAS_STARTED) {
                        Toast.makeText(GongJiJinActivity.this, moxieException.getMessage(), Toast.LENGTH_SHORT).show();
                    } else if (moxieException.getExceptionType() == ExceptionType.SDK_LACK_PARAMETERS) {
                        Toast.makeText(GongJiJinActivity.this, moxieException.getMessage(), Toast.LENGTH_SHORT).show();
                    } else if (moxieException.getExceptionType() == ExceptionType.WRONG_PARAMETERS) {
                        Toast.makeText(GongJiJinActivity.this, moxieException.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                    Log.d("BigdataFragment", "MoxieSDK onError : " + (moxieException != null ? moxieException.toString() : ""));
                }
            });
        });
        rl_select.setOnClickListener(v -> {
            if (mMonth.size() > 0) {
                mDialogManager.show();
            }
        });

        mDialogManager.setOkListener(select -> {
            tv_month.setText(select);
        });


        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int amount = 2000 + progress * 1000;
                mTvAmount.setText(amount + "");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }


        });

        for (int i = 0; i < mAuthViews.size(); i++) {
            int finalI = i;
            mAuthViews.get(i).setOnClickListener(v -> {
                if (mData == null) {
                    showMessage("信息获取失败,请下拉刷新一下");
                    return;
                }
                BpmList bpmList = mData.get(finalI);
                String nodeStatus = bpmList.getNodeStatus();
                if (UserConstant.NS001.equals(nodeStatus)) {
                    switch (finalI) {
                        case 0:
                            if (1 == bpmList.getNodeId()) {
                                startActivity(new Intent(GongJiJinActivity.this, IdCardFrontActivity.class));
                            } else if (2 == bpmList.getNodeId()) {
                                startActivity(new Intent(GongJiJinActivity.this, IdCardBackActivity.class));
                            }
                            break;
                        case 1:
                            startActivity(new Intent(GongJiJinActivity.this, PersonActivity.class));
                            break;
                        case 2:
                            startActivity(new Intent(GongJiJinActivity.this, FaceActivity.class));
                            break;
                        case 3:
                            startActivity(new Intent(GongJiJinActivity.this, PhoneActivity.class));
                            break;
                    }
                } else if (UserConstant.NS002.equals(nodeStatus)) {
                    showMessage("该认证已经完成");
                } else if (UserConstant.NS004.equals(nodeStatus)) {
                    showMessage("认证在审核中,请耐心等待结果");
                } else if (UserConstant.NS006.equals(nodeStatus)) {
                    showMessage("请先完成以上认证");
                }
            });
        }

        mLimitSwipe.setOnRefreshListener(this::initDataOnStart);

    }

    public void closeRefresh() {
        if (mLimitSwipe == null) {
            return;
        }

        if (mLimitSwipe.isRefreshing()) {
            mLimitSwipe.setRefreshing(false);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //用来清理数据或解除引用
        MoxieSDK.getInstance().clear();
    }

    @Override
    protected boolean needFullScreen() {
        return true;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_gongjijin;
    }


}
